import { ArgumentsHost, Catch, ExceptionFilter ,HttpException,HttpStatus,Logger} from '@nestjs/common';
import { HttpAdapterHost } from '@nestjs/core';
import  * as resusetIP from 'request-ip';

// ArgumentsHost: 用于访问当前的请求信息。它提供了一些方法来获取请求的上下文（如 HTTP 请求、WebSocket 等）。
@Catch()
export class AllExceptionFilter<T> implements ExceptionFilter {
  private readonly logger = new Logger();
  constructor(private readonly httpAdapterHost: HttpAdapterHost) {}
  catch(exception: T, host: ArgumentsHost) {
    const {httpAdapter} = this.httpAdapterHost;
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    const request = ctx.getRequest();

    const httpStatus = exception instanceof HttpException ? exception.getStatus() : HttpStatus.INTERNAL_SERVER_ERROR;

    const msg:unknown = exception['response'] || 'Internal Server Error'

    const responseBody = {
      headers: request.headers,
      query: request.query,
      body: request.body,
      parms: request.params,
      // 还可以加一些用户信息
      // ip
      ip:resusetIP.getClientIp(request),
      exceptioin:exception['name'],
      error:msg
    };

    this.logger.error('[toimc]',responseBody);

    httpAdapter.reply(response, responseBody, httpStatus)
  }
}
